import {
  Controller,
  Post,
  UploadedFile,
  UseInterceptors,
  Get,
  Param,
  Delete,
  Body,
  Res,
  UploadedFiles,
} from '@nestjs/common';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname, join } from 'path';
import * as fs from 'fs';
import * as querystring from 'querystring';
import {
  ApiTags,
  ApiBody,
  ApiOperation,
  ApiBearerAuth,
  ApiConsumes,
} from '@nestjs/swagger';
import { Public } from '../../common/decorators/public.decorator';
import { CreateFileManageDto } from '../../dto/file/File.dto';

const storageConfig = {
  destination: './uploads',
  filename: (req, file, cb) => {
    console.log(req.body, 'req.body');

    let fileName = file.originalname;
    if (req?.body?.fileName) {
      fileName = req.body.fileName;
    }
    cb(null, fileName);
  },
};

@ApiTags('文件模块')
@ApiBearerAuth()
@Controller('files')
export class FileUploadController {
  constructor() {
    const uploadFolderPath = './uploads';
    if (!fs.existsSync(uploadFolderPath)) {
      fs.mkdirSync(uploadFolderPath);
    }
  }

  @ApiOperation({ summary: '上传单个文件' })
  @ApiConsumes('multipart/form-data')
  @Post('upload')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage(storageConfig),
    }),
  )
  async uploadFile(
    @UploadedFile() file: Express.Multer.File,
    @Body() fileInfo: CreateFileManageDto,
  ): Promise<any> {
    console.log(file, 'file', fileInfo);

    const fileUrl = `/files/${fileInfo.fileName}`;
    return {
      msg: '上传成功',
      data: {
        fileUrl,
      },
      code: 200,
    };
  }

  @Public()
  @ApiOperation({ summary: '获取文件预览' })
  @Get(':filename')
  async serveFile(
    @Param('filename') filename: string,
    @Res() res,
  ): Promise<any> {
    res.sendFile(filename, { root: 'uploads' });
  }

  @ApiOperation({ summary: '删除文件' })
  @Delete(':filename')
  async deleteFile(@Param('filename') filename: string): Promise<string> {
    try {
      const filePath = `./uploads/${filename}`;
      fs.unlinkSync(filePath);
      return `文件 ${filename} 已成功删除`;
    } catch (error) {
      throw new Error(`删除文件 ${filename} 时出错: ${error.message}`);
    }
  }

  @ApiOperation({ summary: '下载文件' })
  @Get(':filename/download')
  async downloadFile(
    @Param('filename') filename: string,
    @Res() res,
  ): Promise<void> {
    const filePath = `./uploads/${filename}`;
    res.download(filePath, filename); // 发送文件给客户端
  }
}
